package cn.elwy.rcp.ui.table.provider;

import java.lang.reflect.Method;

import cn.elwy.rcp.ui.table.format.ColumnFormat;
import cn.elwy.rcp.ui.table.model.ColumnInfo;
import cn.elwy.rcp.ui.table.model.TableInfo;

public class PropertyLabelProvider extends TablePaneLabelProvider {

  @Override
  public String getColumnText(Object element, int columnIndex) {
    if (element == null) {
      return null;
    }
    TableInfo tableInfo = getTableInfo();
    ColumnInfo columnInfo = tableInfo.getColumnInfo(columnIndex);
    String columnId = columnInfo.getId();
    Class<?> clazz = element.getClass();
    String getMethodName = "get" + Character.toUpperCase(columnId.charAt(0)) + columnId.substring(1);
    try {
      Method getMethod = clazz.getDeclaredMethod(getMethodName);
      getMethod.setAccessible(true);
      Object value = getMethod.invoke(element);
      ColumnFormat format = columnInfo.getColumnFormat();
      if (format != null) {
        value = format.format(value);
      }
      return value == null ? "" : value.toString();
    } catch (Exception e) {
      // 记日志
      return null;
    }
  }

  public Object getCellValue(Object element, int columnIndex) {
    if (element == null) {
      return null;
    }
    TableInfo tableInfo = getTableInfo();
    ColumnInfo columnInfo = tableInfo.getColumnInfo(columnIndex);
    String columnId = columnInfo.getId();
    Class<?> clazz = element.getClass();
    String getMethodName = "get" + Character.toUpperCase(columnId.charAt(0)) + columnId.substring(1);
    try {
      Method getMethod = clazz.getDeclaredMethod(getMethodName);
      getMethod.setAccessible(true);
      return getMethod.invoke(element);
    } catch (Exception e) {
      // 记日志
      return null;
    }
  }
}
